package org.jjj.user.interceptor;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        //1 登录拦截
        //从请求头中获取token
        String token = request.getHeader("token");
        if (StringUtils.isNotBlank(token)){
            Object obj = redisTemplate.opsForValue().get(token);
            if (obj!=null) {
                //刷新token时间
                redisTemplate.opsForValue().set(token,obj,30, TimeUnit.MINUTES);
                return true;//放行
            }
        }
        //如果为空
        //返回一个错误 {“success”:false,"message":"noLogin"}
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.close();
        return false;
    }
}